package manageFriendshipsServlets;

import java.io.IOException; 

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.requestFriendshipSession.FriendshipRequestSessionRemote;
import sessions.friendshipSession.FriendshipSessionRemote;

public class DecideOnFriendshipRequestServlet extends HttpServlet  {
	
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		drawPage(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		drawPage(request, response);
	}

	private void drawPage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String decision;
		int idRequest;
		Context jndiCtx;
		idRequest = Integer.parseInt((String) request.getParameter("idr"));
		decision = (String) request.getParameter("decision");
		if (decision != null && decision.length() > 0) {

			try {
				jndiCtx = new InitialContext();
			 FriendshipRequestSessionRemote friendshipRequestSession = (FriendshipRequestSessionRemote) jndiCtx
						.lookup("Progetto/FriendshipRequestSession/remote");
			 FriendshipSessionRemote friendshipSession = (FriendshipSessionRemote) jndiCtx
						.lookup("Progetto/FriendshipSession/remote");
				if (decision.equals("accept")) {
					// inserisco l'amicizia nella lista dell'utente 
					if (friendshipRequestSession.acceptRequest(idRequest) != 0)
						request.getSession().setAttribute("done", "inserted");
				} else {
					// cancello la richiesta di amicizia
					if (friendshipRequestSession.rejectRequest(idRequest))
						// se la cancellazione � andata a buon fine
						request.getSession().setAttribute("done", "erased");
				}
			} catch (NamingException e) {
				System.out.print("errore nella connessione remota");
				e.printStackTrace();
				request.getSession().setAttribute("done", "error");
			}
		} else
			request.getSession().setAttribute("done", "error");
		response.sendRedirect("/ProgettoWeb/FriendsList.html");
	}

}
